<template>
  <div ref="editorContainer" class="monaco-editor-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'

interface Props {
  modelValue: string
  language?: string
  height?: number
  placeholder?: string
}

const props = withDefaults(defineProps<Props>(), {
  language: 'python',
  height: 400,
  placeholder: '请输入代码...'
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const editorContainer = ref<HTMLElement>()
let editor: any = null

onMounted(async () => {
  if (editorContainer.value) {
    try {
      // 动态导入monaco-editor
      const monaco = await import('monaco-editor')
      
      editor = monaco.editor.create(editorContainer.value, {
        value: props.modelValue,
        language: props.language,
        theme: 'vs-dark',
        fontSize: 14,
        fontFamily: "'Monaco', 'Menlo', 'Ubuntu Mono', monospace",
        minimap: { enabled: false },
        scrollBeyondLastLine: false,
        wordWrap: 'on',
        lineNumbers: 'on',
        roundedSelection: false,
        readOnly: false,
        cursorStyle: 'line',
        automaticLayout: true,
        tabSize: 2,
        insertSpaces: true,
        detectIndentation: false,
        trimAutoWhitespace: true,
        largeFileOptimizations: true,
        suggest: {
          showKeywords: true,
          showSnippets: true,
          showClasses: true,
          showFunctions: true,
          showVariables: true,
          showModules: true,
          showProperties: true,
          showEvents: true,
          showOperators: true,
          showUnits: true,
          showValues: true,
          showConstants: true,
          showEnums: true,
          showEnumMembers: true,
          showColors: true,
          showFiles: true,
          showReferences: true,
          showFolders: true,
          showTypeParameters: true,
          showWords: true
        }
      })

      // 监听内容变化
      editor.onDidChangeModelContent(() => {
        const value = editor.getValue()
        emit('update:modelValue', value)
      })

      // 设置编辑器高度
      editorContainer.value.style.height = `${props.height}px`
      
    } catch (error) {
      console.error('Monaco Editor加载失败，使用备用编辑器:', error)
      // 备用方案：使用简单的textarea
      createFallbackEditor()
    }
  }
})

const createFallbackEditor = () => {
  if (editorContainer.value) {
    const textarea = document.createElement('textarea')
    textarea.value = props.modelValue
    textarea.className = 'code-textarea'
    textarea.placeholder = props.placeholder
    textarea.style.cssText = `
      width: 100%;
      height: ${props.height}px;
      border: none;
      outline: none;
      background: #1e1e1e;
      color: #d4d4d4;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 14px;
      line-height: 1.5;
      padding: 20px;
      resize: none;
      border-radius: 4px;
    `
    
    textarea.addEventListener('input', (e) => {
      const target = e.target as HTMLTextAreaElement
      emit('update:modelValue', target.value)
    })
    
    editorContainer.value.appendChild(textarea)
    editor = textarea
  }
}

onUnmounted(() => {
  if (editor) {
    if (editor.dispose) {
      editor.dispose()
    } else if (editorContainer.value && editor.parentNode) {
      editorContainer.value.removeChild(editor)
    }
  }
})

watch(() => props.modelValue, (newValue) => {
  if (editor) {
    if (editor.setValue) {
      const currentValue = editor.getValue()
      if (currentValue !== newValue) {
        editor.setValue(newValue)
      }
    } else if (editor.value !== newValue) {
      editor.value = newValue
    }
  }
})

watch(() => props.language, async (newLanguage) => {
  if (editor && editor.getModel) {
    try {
      const monaco = await import('monaco-editor')
      const model = editor.getModel()
      if (model) {
        monaco.editor.setModelLanguage(model, newLanguage)
      }
    } catch (error) {
      console.error('Monaco Editor语言切换失败:', error)
    }
  }
})
</script>

<style scoped>
.monaco-editor-container {
  width: 100%;
  height: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.code-textarea {
  tab-size: 2;
}
</style>
